import * as types from '../types';
import axios from 'axios';

/*{
  categoryid: 16313,
  name: '自定义类型',
  create_time: '2017-06-29 09:49:19',
}*/

export default {
  state: {
    data: []
  },
  getters: {
    categories: state => {
      let rsp = {};
      for (let i = 0; i != state.data.length; ++i) {
        rsp[state.data[i].categoryid] = state.data[i];
      }
      return rsp;
    }
  },
  mutations: {
    [types.SET_CATEGORIES]: (state, payloads) => {
      //state.data.splice(0, state.data.length);
      state.data = [];
      for (let i = 0; i != payloads.length; ++i) {
        state.data.push(payloads[i]);
      }
    },
    [types.ADD_CATEGORY]: (state, payload) => {
      state.data.push(payload);
    }
  },
  actions: {
    load_categories: ({ commit }) => {
      axios.get("/categories/").then(response => {
        commit(types.SET_CATEGORIES, response.data);
      }).catch(err => {
        console.log('load categories failed.');
        console.error(err);
      });
    },
    add_category: ({ commit }, payload) => {
      return new Promise((resolve, reject) => {
        axios.post("/categories/", payload).then(response => {
          commit(types.ADD_CATEGORY, response.data);
          resolve(response);
        }).catch(err => {
          console.log('add category failed');
          reject(err);
        });
      });
    },
  }
}